<?php

namespace App\Domain\Customer\Services;

class VerificationCodeDes
{

    /**
     * @var string
     */
    private $key;

    public function __construct()
    {
        $this->key = config("des.code_key");
    }


    public function encryptDes($data)
    {
        $paddedData = $this->pad($data);
        $opts = OPENSSL_ZERO_PADDING | OPENSSL_RAW_DATA;
        return base64_encode((openssl_encrypt($paddedData, 'DES-ECB', $this->key, $opts)));
    }

    public function decryptDes($data)
    {
        $data = hex2bin($data);
        $opts = OPENSSL_ZERO_PADDING | OPENSSL_RAW_DATA;
        return $this->unpad(openssl_decrypt($data, 'DES-ECB', $this->key, $opts));
    }

    private function pad($text)
    {
        $blockSize = 8;
        $length = strlen($text);
        $pad = $blockSize - ($length % $blockSize);
        return str_pad($text, $length + $pad, chr($pad));
    }

    private function unpad($text)
    {
        $length = ord($text[strlen($text) - 1]);
        return substr($text, 0, -$length);
    }
}

